package com.ljw.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ljw.common.to.mq.OrderTo;
import com.ljw.common.to.mq.StockDetailTo;
import com.ljw.common.to.mq.StockLockedTo;
import com.ljw.common.utils.R;
import com.ljw.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.ljw.gulimall.ware.entity.WareOrderTaskEntity;
import com.ljw.gulimall.ware.exception.NoStockException;
import com.ljw.gulimall.ware.feign.OrderFeignService;
import com.ljw.gulimall.ware.service.WareOrderTaskDetailService;
import com.ljw.gulimall.ware.service.WareOrderTaskService;
import com.ljw.gulimall.ware.vo.*;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljw.common.utils.PageUtils;
import com.ljw.common.utils.Query;

import com.ljw.gulimall.ware.dao.WareSkuDao;
import com.ljw.gulimall.ware.entity.WareSkuEntity;
import com.ljw.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
@RabbitListener(queues = {"stock.release.stock.queue"})
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService orderTaskService;

    @Autowired
    private WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<WareSkuEntity> wrapper = new LambdaQueryWrapper<>();
        String skuId = (String) params.get("skuId");
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isBlank(skuId)){
            wrapper.eq(WareSkuEntity::getSkuId, skuId);
        }
        if (!StringUtils.isBlank(wareId)){
            wrapper.eq(WareSkuEntity::getWareId, wareId);
        }
        IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params),wrapper);

        return new PageUtils(page);
    }

    /**
     * 查询skuIds是否有库存
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        LambdaQueryWrapper<WareSkuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(WareSkuEntity::getSkuId, skuIds);
        List<WareSkuEntity> wareSkuEntities = baseMapper.selectList(wrapper);
        List<SkuHasStockVo> skuHasStockVoList = new ArrayList<>();
        wareSkuEntities.forEach(wareSkuEntity -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(wareSkuEntity.getSkuId());
            if ((wareSkuEntity.getStock() == null ? 0 : wareSkuEntity.getStock()) - (wareSkuEntity.getStockLocked() == null ? 0 : wareSkuEntity.getStockLocked()) > 0){
                skuHasStockVo.setHasStock(true);
            }
            else {
                skuHasStockVo.setHasStock(false);
            }
            skuHasStockVoList.add(skuHasStockVo);
        });
        return skuHasStockVoList;
    }

    /**
     * ollbackFor = NoStockException.class
     * 默认只要是运行时异常都会回滚
     * 为某个订单锁定库存
     *
     * 库存解锁场景
     * 1、下订单成功，订单过期没有支付，被系统自动取消
     * 2、用户手动取消订单
     * 3、下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，之前锁定的库存就要回滚。
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单的详情
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);
        //1、按照下单的收货地址，找到一个就近仓库，锁定库存。
        //1、找到每个商品哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(orderItemVo -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = orderItemVo.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(orderItemVo.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            Integer num = hasStock.getNum();
            if (wareIds == null || wareIds.size() == 0){
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            //1、如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发给mq
            //2、锁定失败，前面保存的工作单信息就回滚了，发送出去的消息也没问题，即使要解锁Id也要去数据中查记录，但数据库中不存在
            for (Long wareId : wareIds) {
                //成功就返回1，否侧就是0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, num);
                if (count == 1){
                    skuStocked = true;
                    //TODO 库存锁定成功，告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    orderTaskDetailService.save(wareOrderTaskDetailEntity);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTo);
                    stockLockedTo.setId(taskEntity.getId());
                    stockLockedTo.setStockDetailTo(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                }else {
                    //当前仓库锁库存失败，重试下一个仓库
                }
            }
            if (skuStocked == false){
                //当前商品所有仓库没有锁住库存
                throw new NoStockException(skuId);
            }
        }

        //3、走到这里肯定是全部商品锁住库存成功

        return true;
    }

    /**
     * 1、库存自动解锁
     *   下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，之前锁定的库存就要回滚。
     */
    @Override
    public void unlockStock(StockLockedTo to) {
        Long id = to.getId(); //库存工作单的id;
        StockDetailTo stockDetailTo = to.getStockDetailTo();
        Long detailId = stockDetailTo.getId();

        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if (byId != null){
            /**
             * 解锁
             * 1、查询数据库关于这个订单的信息
             * 有：证明库存锁定成功了
             * 解锁订单的情况： 没有这个订单。必须解锁
             *               有这个订单，判定订单状态，订单状态为已取消就解锁库存
             * 没有：库存锁定失败了，库存回滚了，订单也会回滚，这种情况无需解锁
             */
            String orderSn = orderTaskService.getById(id).getOrderSn();
            R order = orderFeignService.getOrderStatus(orderSn);
            if (order.getCode() == 0){
                OrderVo orderData = order.getData(new TypeReference<OrderVo>() {});
                if (orderData == null || orderData.getStatus() == 4){
                    ////订单不存在或订单已经被取消，被取消的订单才能解锁库存
                    if (byId.getLockStatus() == 1){
                        //当前库存工作单详情，状态1，已锁定但是未解锁才可以解锁
                        unLockedStock(stockDetailTo.getSkuId(), stockDetailTo.getWareId(), stockDetailTo.getSkuNum(), detailId);
                    }
                }
            }
            else {
                //远程服务调用失败，抛出异常，解锁库存失败，消息回到队列中
                throw new RuntimeException("远程服务调用失败");
            }
        }
    }

    //防止订单服务卡顿，导致订单状态消息一直改不了，库存消息优先到期，导致卡顿订单，永远无法解锁库存
    @Override
    @Transactional
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新库存的状态，防止重复解锁库存
        WareOrderTaskEntity orderTaskEntity = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long orderTaskEntityId = orderTaskEntity.getId();
        List<WareOrderTaskDetailEntity> entities = orderTaskDetailService.list(new LambdaQueryWrapper<WareOrderTaskDetailEntity>()
                .eq(WareOrderTaskDetailEntity::getTaskId, orderTaskEntityId)
                .eq(WareOrderTaskDetailEntity::getLockStatus, 1));
        for (WareOrderTaskDetailEntity entity : entities) {
            this.unLockedStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }

    }

//    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
//        System.out.println("收到解锁库存的消息");
//        Long id = to.getId(); //库存工作单的id;
//        StockDetailTo stockDetailTo = to.getStockDetailTo();
//        Long detailId = stockDetailTo.getId();
//
//        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
//        if (byId != null){
//            /**
//             * 解锁
//             * 1、查询数据库关于这个订单的信息
//             * 有：证明库存锁定成功了
//             * 解锁订单的情况： 没有这个订单。必须解锁
//             *               有这个订单，判定订单状态，订单状态为已取消就解锁库存
//             * 没有：库存锁定失败了，库存回滚了，订单也会回滚，这种情况无需解锁
//             */
//            String orderSn = orderTaskService.getById(to.getId()).getOrderSn();
//            R order = orderFeignService.getOrderStatus(orderSn);
//            if (order.getCode() == 0){
//                OrderVo orderData = order.getData(new TypeReference<OrderVo>() {});
//                if (orderData == null || orderData.getStatus() == 4){
//                    ////订单不存在或订单已经被取消，被取消的订单才能解锁库存
//                    unLockedStock(stockDetailTo.getSkuId(), stockDetailTo.getWareId(), stockDetailTo.getSkuNum(), detailId);
//                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//                }
//            }else {
//                //消息拒绝以后重新返回到队列中，让别人继续消费解锁。
//                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
//            }
//        }else {
//            //无需解锁
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//        }
//    }


    private void unLockedStock(Long skuId, Long wareId, Integer num, Long taskDetailId){
        //库存解锁
        baseMapper.unLockedStock(skuId, wareId, num);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(taskDetailId);
        wareOrderTaskDetailEntity.setLockStatus(2); //变为已解锁
        orderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;

    }

}